<?php
namespace Tools\Controller;
use Common\Controller\AdminbaseController;

/**
 * 合作伙伴分类
 */
class AdminPartnerCateController extends AdminbaseController{
	
	protected $cate_model;

	public function _initialize() {
		parent::_initialize();
		$this->cate_model = D("ToolsPartnerCate");
	}

	/**
	 * 合作伙伴分类列表
	 */
	public function index() {
		$list = $this->cate_model -> order(array('orderby'=>'asc')) -> select();
		$this -> assign('list', $list);
		$this -> display ('index');
	}

	//填加
	public function add() {
		$this -> _modify();
	}

	//修改
	public function edit() {
		$this -> _modify();
	}

	private function _modify() {

		$cate_id = I('cate_id');
		
		if (IS_POST) {
			$validate = array(
				array('cate_name', 'require', '分类名不能为空'),
			);
			$result = array('status' => TRUE, 'info' => '', 'url' => '');
			
			$this->cate_model -> field('cate_name,orderby');
			
			if ($this->cate_model -> validate($validate) -> create()) {
				if (!$cate_id) {
					$insert_id = $this->cate_model -> add();
					if ($insert_id) {
						$result['info'] = '添加成功';
					} else {
						$result['status'] = FALSE;
						$result['info'] = '添加失败';
					}
				} else {
					if($this->cate_model -> where(array('cate_id' => $cate_id)) -> save()) {
						$result['info'] = '保存成功';
					} else {
						$result['status'] = FALSE;
						$result['info'] = '保存失败';
					}
				}
			} else {
				//返回错误提示
				$result['status'] = FALSE;
				$result['info'] = $this->cate_model -> getError();
			}
			
			if ($result['status']) {
				$this -> success($result['info'],U('Tools/AdminPartnerCate/index'));
			} else {
				$this -> error($result['info']);
			}
		}

		$select_cates = $this->cate_model -> select();
		$cate = $cate_id ? $this->cate_model -> find($cate_id) : array();
		
		$this -> assign('cate', $cate);
		$this -> assign('select_cates', $select_cates);
		$this -> display('AdminPartnerCate/form');
	}


	/**
	 * 合作单位分类列表的批量操作
	 * @param string $type	处理类型 order排序,delete删除
	 */
	public function indexBat($type='order') {
		//排序
		if ($type == 'order') {
			$order_array = I('post.orderby');
			if ($this->cate_model->saveBatch($order_array, 'cate_id', 'orderby') !== FALSE) {
				$this -> success('排序成功');
			} else {
				$this -> error('排序出错');
			}
		}
		if ($type == 'delete') {
			$ids = I('post.ids');
			if ($this->cate_model -> delete(implode(',',$ids)) !== FALSE) {
				$this -> success('删除成功');
			} else {
				$this -> error('删除失败');
			}
		}
	}

	//删除
	public function delete() {
		$cate_id = I('cate_id');
		$result = $this->cate_model-> delete($cate_id);	
		$data = array(
			'status' => $result ? true : false,
			'info' => $result ? '' : '删除失败，ID：'.$cate_id,
			'url' => '',
		);
		$this -> ajaxReturn($data);
	}

}